<template>
  <div>
    <el-card class="box-card"  shadow="never">
      <div  slot="header" class="clearfix" style="display: flex; align-items: center; justify-content: space-between;">
        <span style="flex-grow: 3">客户信息</span>
        <el-input style="flex-grow: 1; width: auto"  size="mini"
                  placeholder="客户名称或者电话搜索"
                  prefix-icon="el-icon-search">
        </el-input>
        <el-button type="primary" size="mini" @click="dialogAddCustomVisible = true" style="flex-grow: 0;">新建</el-button>
      </div>

      <el-table :data="tableGuest" stripe size="medium" border
                ref="multipleTable"
                tooltip-effect="dark"
                style="width: 100%"
                @selection-change="handleSelectionChange">
        <el-table-column label="序号"
            type="index"
            width="100">
        </el-table-column>
        <el-table-column
            prop="companyName"
            label="客户全称">
        </el-table-column>
        <el-table-column
            prop="createBy"
            label="创建人"
            show-overflow-tooltip>
        </el-table-column>
        <el-table-column
            prop="updateTime"
            label="更新时间"
            show-overflow-tooltip>
        </el-table-column>
        <el-table-column type="expand"
                         label="历史需求" width="150">
          <template slot-scope="scope">
            <el-descriptions v-for="(item ,index) in scope.row.demandHistory" direction="vertical" :column="5" border size="mini" >
              <el-descriptions-item label="需求编号">{{item.sn}}</el-descriptions-item>
              <el-descriptions-item label="创建时间">{{ item.createTime }}</el-descriptions-item>
              <el-descriptions-item label="项目负责人">{{item.head}}</el-descriptions-item>
              <el-descriptions-item label="需求类型">{{item.demandType}}</el-descriptions-item>
              <el-descriptions-item label="当前状态">{{item.demandDes}}</el-descriptions-item>
            </el-descriptions>

            <el-button type="text" size="mini" style="margin: 0 20px"
                       @click="addDemand(scope.row.companyName)">新增需求
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-dialog title="新建客户" :visible.sync="dialogAddCustomVisible" :close-on-click-modal="false" width="60%">
        <el-form :model="customDTO" label-position="left" label-width="100px" size="mini" :inline="true">
          <el-row>
            <el-col :span="8">
              <el-form-item label="公司全称">
                <el-input v-model="customDTO.companyName" style="width: 250px"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="统一社会信用代码" label-width="130px">
                <el-input v-model="customDTO.companyCreditCode" style="width: 220px"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="企业类型">
                <el-select v-model="customDTO.companyType" placeholder="请选择" style="width: 250px">
                  <el-option
                      v-for="item in companyTypeOptions"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="8">
              <el-form-item label="法定代表人">
                <el-input v-model="customDTO.companyLegalPerson" style="width: 250px"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="经营范围">
                <el-input v-model="customDTO.companyBusinessScope" style="width: 250px"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="注册资本">
                <el-input v-model="customDTO.companyRegisteredCapital" style="width: 250px"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="8">
              <el-form-item label="成立日期">
                <el-date-picker
                    v-model="customDTO.companyEstablishmentDate"
                    type="date"
                    placeholder="选择日期"
                    value-format="yyyy/MM/dd" style="width: 250px">
                </el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="营业期限">
                <el-input v-model="customDTO.companyBusinessTerm" style="width: 250px"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="住所">
                <el-input v-model="customDTO.companyAddress" style="width: 250px"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="8">
              <el-form-item label="营业执照">
                <el-upload
                    class="upload-demo"
                    :action="uploadAction"
                    :on-preview="handlePreview"
                    :on-remove="handleRemove"
                    :on-success="handleUploadSuccess"
                    :file-list="licenseFileList"
                    list-type="picture">
                  <el-button type="text">点击上传</el-button>
                </el-upload>
              </el-form-item>
            </el-col>
            <el-col :span="16">
              <el-form-item label="备注（待定）">
                <el-input v-model="customDTO.companyDes" style="width: 500px"></el-input>
              </el-form-item>
            </el-col>
          </el-row>

          <!-- 联系人信息字段 -->
          <el-form-item label="联系人">
            <el-form v-for="(item, index) in contacts" :key="index" size="mini"
                     label-width="60px"
                     style="border: 1px solid #eaeaea; box-sizing: border-box; width: 100%; padding: 15px" :inline="true">
              <el-form-item label="姓名">
                <el-input v-model="item.contactsName" style="width: 100px"></el-input>
              </el-form-item>
              <el-form-item label="职务">
                <el-input v-model="item.contactsDuties" style="width: 120px"></el-input>
              </el-form-item>
              <el-form-item label="电话">
                <el-input v-model="item.contactsMobile" style="width: 120px"></el-input>
              </el-form-item>
              <el-form-item label="邮箱">
                <el-input v-model="item.contactsMail" style="width: 150px"></el-input>
              </el-form-item>
              <el-form-item label="决策">
                <el-select v-model="item.contactsDecisionType" style="width: 120px">
                  <el-option
                      v-for="item in optionsDecisionType"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value">
                  </el-option>
                </el-select>
              </el-form-item>
              <br>
              <el-form-item>
                <el-button @click="removeContact(index)" type="text">移除联系人</el-button>
                <el-button @click="addContact" type="text">新增联系人</el-button>
              </el-form-item>
            </el-form>
          </el-form-item>
          <!-- 收货地址信息字段 -->
          <el-form-item label="收货地址">
            <el-form v-for="(item, index) in receivingAddresses" :key="index" size="mini"
                     label-width="60px"
                     style="border: 1px solid #eaeaea; box-sizing: border-box; width: 100%; padding: 15px" :inline="true">
              <el-form-item label="收货人">
                <el-input v-model="item.cargoReceiver" style="width: 100px"></el-input>
              </el-form-item>
              <el-form-item label="手机号">
                <el-input v-model="item.cargoReceiverMobile" style="width: 120px"></el-input>
              </el-form-item>
              <el-form-item label="地址">
                <el-input v-model="item.address" style="width:500px"></el-input>
              </el-form-item>

              <br>
              <el-form-item>
                <el-button @click="removeAddress(index)" type="text">移除地址</el-button>
                <el-button @click="addAddress" type="text">新增地址</el-button>
              </el-form-item>
            </el-form>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogAddCustomVisible = false" size="mini">取 消</el-button>
          <el-button type="primary" @click="addCustom()" size="mini">确 定</el-button>
        </div>
      </el-dialog>
      <el-dialog title="新建需求" :visible.sync="dialogAddDemandVisible">
        <el-form :model="demand" label-width="100px" size="mini">
          <el-form-item label="客户名称">
            <el-input :value="demand.companyName" :disabled="true"></el-input>
          </el-form-item>
          <el-form-item label="需求编号">
            <el-input type="text" v-model="demand.sn"></el-input>
          </el-form-item>
          <el-form-item label="项目负责人">
            <el-input v-model="demand.head"></el-input>
          </el-form-item>
          <el-form-item label="协作人">
            <template v-for="(item,index) in demandSupporters">
              <el-input v-model="item.supporterContent" placeholder="备注（非必填）" style="margin-bottom: 10px">
                <el-select v-model="item.supporterType" slot="prepend" placeholder="协作类型"
                           style="width: 110px;margin-right: 15px;">
                  <el-option label="机械设计" value="机械设计"></el-option>
                  <el-option label="焊接工艺" value="焊接工艺"></el-option>
                  <el-option label="装备交付" value="装备交付"></el-option>
                </el-select>
                <el-select placeholder="请选择人员" v-model="item.supporter" slot="prepend"
                           style="width: 110px;">
                  <el-option-group
                      v-for="group in optionsSupporter"
                      :key="group.label"
                      :label="group.label">
                    <el-option
                        v-for="item in group.options"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value">
                    </el-option>
                  </el-option-group>
                </el-select>
                <el-button icon="el-icon-close" size="mini" type="text" @click="removeSupporterItem(index)"
                           slot="append"></el-button>
              </el-input>
            </template>
            <el-button type="primary" size="mini" icon="el-icon-plus" @click="addSupporterItem"></el-button>
          </el-form-item>
          <el-form-item label="需求类型">
            <el-radio v-model="demand.demandType" label="装备采购">装备采购</el-radio>
            <el-radio v-model="demand.demandType" label="产品焊接">产品焊接</el-radio>
            <el-radio v-model="demand.demandType" label="技术服务">技术服务</el-radio>
            <el-radio v-model="demand.demandType" label="搅拌工具">搅拌工具</el-radio>
          </el-form-item>
          <el-form-item v-if="demand.demandType === '装备采购'">
            <el-input disabled="true" :value="demand.eqDes"></el-input>
          </el-form-item>
          <el-form-item v-if="demand.demandType === '产品焊接'">
            <el-input disabled="true" :value="demand.prDes"></el-input>
          </el-form-item>
          <el-form-item v-if="demand.demandType === '技术服务'">
            <el-input disabled="true" :value="demand.teDes"></el-input>
          </el-form-item>
          <el-form-item v-if="demand.demandType === '搅拌工具'">
            <el-input disabled="true" :value="demand.toolDes"></el-input>
          </el-form-item>
          <el-form-item label="需求描述">
            <el-input v-model="demand.demandDes" type="textarea"></el-input>
            <div style="margin-top: 15px;">
              <el-upload
                  class="upload-demo"
                  drag
                  action="https://localhost:8080/post/"
                  multiple>
                <i class="el-icon-upload"></i>
                <div class="el-upload__text">将客户需求文件拖到此处，或<em>点击上传</em></div>
              </el-upload>
            </div>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogAddDemandVisible = false" size="mini">取 消</el-button>
          <el-button type="primary" @click="submitDemand()" size="mini">确 定</el-button>
        </div>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
import {optionsHeader} from "@/utils/optionsHeader";
export default {
  name: "GuestInfo",
  data() {
    return {
      activeName: 'first',
      dialogAddCustomVisible: false,
      dialogAddDemandVisible: false,
      licenseFileList: [],
      uploadAction: `${process.env.VUE_APP_API_BASE_URL}/file/upload`,
      customDTO: {
        companyName: '',
        companyCreditCode: '',
        companyType: '',
        companyLegalPerson: '',
        companyBusinessScope: '',
        companyRegisteredCapital: '',
        companyEstablishmentDate: '',
        companyBusinessTerm: '',
        companyAddress: '',
        companyLicense: '',
        companyDes: ''
      },
      contacts: [{
        contactsName: '',
        contactsDuties: '',
        contactsMobile: '',
        contactsMail: '',
        contactsDecisionType: ''
      }],
      receivingAddresses: [{
        address: '',
        cargoRreceiver: '',
        cargoReceiverMobile: ''
      }],
      valueAddress: [],
      optionsAddress: [],
      companyTypeOptions: [
        {
          value: '有限责任公司',
          label: '有限责任公司'
        },
        {
          value: '股份有限公司',
          label: '股份有限公司'
        }, {
          value: '个人独资企业',
          label: '个人独资企业'
        },
        {
          value: '合伙企业',
          label: '合伙企业'
        },
        {
          value: '分公司',
          label: '分公司'
        }],
      optionsDecisionType: [
        {
          value: '关键决策人',
          label: '关键决策人'
        }, {
          value: '商务决策人',
          label: '商务决策人'
        }, {
          value: '技术决策人',
          label: '技术决策人'
        }, {
          value: '使用人',
          label: '使用人'
        },
        {
          value: '意见影响人',
          label: '意见影响人'
        },
        {
          value: '财务决策人',
          label: '财务决策人'
        }
      ],
      optionsSupporter: optionsHeader,
      tableGuest: [
        {
          companyName: '',
          createBy: '',
          updateTime: '',
          demandHistory: [
            {
              sn: '',
              createTime: '',
              head: '',
              demandType: '',
              demandDes: ''
            }
          ]
        }
      ],
      dialogImageUrl: '',
      dialogVisible: false,
      demand: {
        companyName: '',
        sn: '',
        head: '',
        demandType: '1',
        eqDes: '填写说明：装备型号；数量；工作台尺寸；需求时间……',
        toolDes: '填写说明：型号；数量……',
        teDes: '填写说明：……',
        prDes: '填写说明：……',
        demandDes: '',
        demandAttarch: ''
      },
      demandSupporters: [{supporterContent: '', supporterType: '', supporter: ''}],
    }
  },
  methods: {
    addContact() {
      this.contacts.push({
        contactsName: '',
        contactsDuties: '',
        contactsMobile: '',
        contactsMail: '',
        contactsDecisionType: ''
      });
    },
    removeContact(index) {
      if (this.contacts.length > 1) {
        this.contacts.splice(index, 1);
      }
    },
    addAddress() {
      this.receivingAddresses.push({
        address: '',
        cargoReceiver: '',
        cargoReceiverMobile: ''
      });
    },
    removeAddress(index) {
      if (this.receivingAddresses.length > 1) {
        this.receivingAddresses.splice(index, 1);
      }
    },
    addDemand(name) {
      this.dialogAddDemandVisible = true
      this.demand.companyName = name
    },
    //点击需求行，携带需求编号和公司名称发给需求详细组件，注意这里的companyName参数是外层表格，参数传递稍微复杂一些
    handleRowClick(row, parentRow) {
      const sn = row.sn // 假设这是你获取sn值的方式
      const companyName = parentRow.companyName
      if (sn) {
        this.$router.push({name: 'HistoryDemand', query: {sn, companyName}});
      } else {
        console.error('SN值未定义或为空');
      }
    },
    addSupporterItem() {
      this.demandSupporters.push({supporterContent: '', supporterType: '', supporter: ''})
    },
    removeSupporterItem(index) {
      this.demandSupporters.splice(index, 1)
    },
    //新增需求方法，包含需求和协作人两部分信息
    submitDemand() {
      const demandData = {demand: this.demand, demandSupporters: this.demandSupporters}
      console.log(demandData);
      this.dialogAddCustomVisible = false
      this.$http.post("/demand/add", demandData).then((response) => {
        if (response.data.code == 1) {
          alert("新增需求成功")
        } else {
          alert("需求增加失败")
        }
      })
    },
    handleUploadSuccess(response, file, fileList) {
      const filePath = response.data;
      this.licenseFileList.push({name: file.name, url: filePath});
      console.log(this.licenseFileList);
      this.custom.companyLicense = this.licenseFileList.map(function (file) {
        return file.url;
      }).join(',');
    },

    handleRemove(file, fileList) {
      console.log(file, fileList);
    },
    handlePreview(file) {
      console.log(file);
    },
    handleExceed(files, fileList) {
      this.$message.warning(`当前限制选择 3 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`);
    },
    beforeRemove(file, fileList) {
      return this.$confirm(`确定移除 ${file.name}？`);
    },
    //新建客户方法，包含公司和联系人两部分信息
    addCustom() {
      const formData = {customDTO: this.customDTO, contacts: this.contacts, receivingAddresses: this.receivingAddresses}
      console.log(formData)
      this.dialogFormVisible = false
      this.$http.post("/custom/add", formData,
          {
            headers: {
              'Content-Type': 'application/json',
            }
          }).then((response) => {
        if (response.data.code == 1) {
          alert("提交完毕")
        } else {
          alert("提交失败");
          console.error(response.data.data);
        }
      })
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    }
  },
  created() {
    this.$http.get("/custom").then((response) => {
      if (response.data.code == 1) {
        this.tableGuest = response.data.data
        console.log(this.tableGuest)
      }
    })
  }
}
</script>
<style scoped>
.clearfix:before,
.clearfix:after {
  display: table;
  content: "";
}
::v-deep .el-card {
  border: none !important;
}

::v-deep .el-card__body {
  padding: 0 !important;
}

::v-deep .el-card__header {
  padding: 20px 0 !important;
  border: none !important;
}
.clearfix:after {
  clear: both
}

</style>